#include "player.h"

Player::Player(QObject *parent):QObject(parent)
{
    m_player = new QMediaPlayer(this);
    connect(m_player, SIGNAL(stateChanged(QMediaPlayer::State)), this, SLOT(slotStateChanged(QMediaPlayer::State)));

    m_stateCheckTimer = new QTimer(this);
    connect(m_stateCheckTimer, SIGNAL(timeout()), this, SLOT(slotCheckState()));
    m_stateCheckTimer->start(500);

    m_desiredState = Stopped;
}

Player::~Player()
{

}

void Player::play(const QUrl &location){
    if(m_player->media() == QMediaContent(location))
        m_player->play();
    else{
        m_player->setMedia(QMediaContent(location));
        m_player->play();
    }
    emit playing();
    printf("emit playing()\n");
    m_desiredState = Playing;

}

void Player::play(){
    if(!m_player->media().isNull()){
        //if(m_player->state() == QMediaPlayer::PausedState)

        m_player->play();
        emit playing();
        printf("emit playing()\n");
        m_desiredState = Playing;
    }
}

void Player::stop(){
    m_player->stop();
    emit stopped();
    m_desiredState = Stopped;
}

void Player::pause(){
    if(!m_player->media().isNull()){
        m_player->pause();
        emit paused();
        m_desiredState = Paused;
    }
}

//This will also change m_desiredState, because upward forces are notified and should handle this.
void Player::slotStateChanged(QMediaPlayer::State state){
    /*printf("slotStateChanged(%s)\n", state==QMediaPlayer::StoppedState? "stopped" : (state == QMediaPlayer::PlayingState ? "playing" : "paused"));*/
    switch(state){
        case QMediaPlayer::StoppedState:
            m_desiredState = Stopped;
            printf("emit stopped()\n");
            //emit stopped();//Commented this out, as stopped() is connected to next().
            break;
        /*case QMediaPlayer::PlayingState:
            m_desiredState = Playing;
            emit playing();
            printf("emit playing()\n");

            break;
        case QMediaPlayer::PausedState:
            m_desiredState = Paused;
            printf("emit paused()\n");
            emit paused();
            break;*/

    }
}

//Come to think of it, this function should not be necessary, as slotStateChanged should be able to deal with things.
//I'll fill this in later if I consider it to be necessary
void Player::slotCheckState(){
    QMediaPlayer::State state = m_player->state();
    if(state == QMediaPlayer::PlayingState && m_desiredState != Playing){

    }else if(state == QMediaPlayer::PausedState && m_desiredState != Paused){

    }else if(state == QMediaPlayer::StoppedState && m_desiredState != Stopped){

    }
}
